import './3rd/opentype.min.js'

const activityDOM = document.getElementById('activity')
const mainDOM = document.getElementById('main')

const inputDOM = document.getElementById('input')

const outputDOM = document.getElementById('output')

const importDOM = document.getElementById('import')
const exportDOM = document.getElementById('export')

/**
 * 输入字体文件整集
 */
var fullset

/**
 * 子集构造选项
 */
var subsetOpt

/**
 * 字体预览ObjectURL
 */
var fullsetURL

/**
 * 预览orgFontFace
 */
var orgFontFace

var subsetBuffers

var subsetName

/**
 * opentype.js需要的首位空字形
 * @type {opentype.Glyph}
 */
const notdefGlyph = new opentype.Glyph({
	name: '.notdef',
	advanceWidth: 650,
	path: new opentype.Path()
})

activityDOM.addEventListener('click', () => {
	upload()
})

importDOM.addEventListener('click', () => {
	upload()
})

inputDOM.addEventListener('input', e => {
	const v = e.target.value

	outputDOM.textContent = v

	subsetBuffers = null
})

exportDOM.addEventListener('click', e => {
	if (!subsetBuffers) {
		gen()
	}

	window.preload.downloadFile(subsetBuffers, subsetName)
		.then(e => {
			utools.showNotification('导出成功')
		})
})

const upload = function() {
	window.preload.openFile({
		title: '请选择字体文件',
		buttonLabel: '选择',
		filters: [{
			name: '字体',
			extensions: ['ttf', 'otf', 'woff']
		}]
	}).then(file => {
		scan(file)

		activityDOM.style.display = 'none'
		mainDOM.style.display = 'block'
	}).catch(e => {
		console.error("打开文件失败", e);
	})
}

const gen = function() {
	//输入文本去重
	const set = new Set(outputDOM.textContent)

	var input = ''
	set.forEach(c => {
		input += c
	})

	//构建子集字形
	subsetOpt.glyphs = [notdefGlyph].concat(fullset.stringToGlyphs(input))

	subsetBuffers = new opentype.Font(subsetOpt).toArrayBuffer()
}

const scan = async function(file) {
	const arr = file.name.split('.')
	arr.splice(arr.length - 1, 0, 'subset')
	subsetName = arr.join('.')

	const arrayBuffer = await readFile(file)
	fullset = opentype.parse(arrayBuffer)

	subsetOpt = {
		familyName: fullset.getEnglishName('postScriptName'),
		styleName: fullset.getEnglishName('fontSubfamily'),
		unitsPerEm: fullset.unitsPerEm,
		ascender: fullset.ascender,
		descender: fullset.descender,
		fsSelection: 0
	}

	if (fullsetURL) {
		//释放url
		URL.revokeObjectURL(fullsetURL)
	}
	//创建子集blob和对应ObjectURL
	fullsetURL = URL.createObjectURL(new Blob([arrayBuffer]))

	if (orgFontFace) {
		//删除上个临时orgFontFace
		document.fonts.delete(orgFontFace)
	}
	//构建预览用orgFontFace
	orgFontFace = new FontFace('_tmpfont', `url(${fullsetURL})`)

	document.fonts.add(orgFontFace)
	outputDOM.style.fontFamily = '_tmpfont'

	subsetBuffers = null
}

const readFile = function(blob) {
	var onResolve, onReject
	const promise = new Promise((resolve, reject) => {
		onResolve = resolve
		onReject = reject
	})

	const fileReader = new FileReader()

	fileReader.addEventListener('loadend', e => {
		if (e.target?.result) {
			onResolve(e.target.result)
		} else {
			onReject()
		}
	})

	fileReader.readAsArrayBuffer(blob)

	return promise
}